package com.ckd.flyingtrip.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.Tools;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 启动页
 * Created by HITMAN on 2018/7/18.
 */
public class SplashActivity extends BaseActivity {

    @BindView(R.id.tv_tiaoguo)
    TextView tvTiaoguo;
    private int num = 3;
    private CountDownTimer countDownTimer;

    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };
    private static final int PERMISSON_REQUESTCODE = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        checkPermissions(needPermissions);
    }

    private void info() {
        tvTiaoguo.setVisibility(View.VISIBLE);
        tvTiaoguo.setText("跳过" + num);
        tvTiaoguo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                    countDownTimer.onFinish();
                    countDownTimer = null;
                }
                startInt();
            }
        });


        countDownTimer = new CountDownTimer(1000 * 3, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                num--;
                tvTiaoguo.setText("跳过" + num);
            }

            @Override
            public void onFinish() {
                startInt();
            }
        }.start();
    }


    //
//
    /*
     * 未登录跳转登录页
     * */
    public void startInt() {
        if (!Tools.isEmpeyNull(BcUtils.getUid())) {
            Tools.startIntent(SplashActivity.this, UserLogInActivity.class);
        } else {
//            startAction(MainActivity.class);
            startAction(MainNewActivity.class);
        }
        setResult(RESULT_OK);
        finish();
    }

    /**
     * @param permissions
     * @since 2.5.0
     */
    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
                            int.class});
                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                } else {
                    info();
                }
            } else {
                info();
            }
        } catch (Throwable e) {
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer) checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean) shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否所有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                //                showMissingPermissionDialog();
                Toast.makeText(this, "权限被拒绝，请手动授予权限", Toast.LENGTH_SHORT).show();
//                checkPermissions(needPermissions);
            } else {

                info();

            }
        }
    }
}
